package com.wander.nio.chat;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

public class MyClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress("localhost",8888));
            //启动一个线程监听群发消息
            new Thread(new ReceiveTask( socket)).start();

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                OutputStream os = socket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF(msg);
                dos.flush();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static class ReceiveTask implements Runnable {
        private Socket socket;

        public ReceiveTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    InputStream is = socket.getInputStream();
                    DataInputStream dis = new DataInputStream(is);
                    String msg = dis.readUTF();
                    System.out.println("收到消息：" + msg);
                } catch (IOException e) {
                    System.out.println(e);
                    System.out.println("当前客户端退出");
                    break;
                }
            }
        }
    }
}
